from flask import Blueprint, request, jsonify
from .Cmod import *
from .Cmod_pic import *
from .Cmod_user import *
from .Cmod_express import *

blue_search = Blueprint('search', __name__)


# 根据用户昵称；文章，问题的标题和内容来实现的模糊搜索
@blue_search.route('/api/search/bookshelf', methods=['POST', 'GET'])
def search_bookshelf_by_title():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    search_term = data.get('search')
    page_num = int(data.get('page_num', 0))

    bookshelfs = db.session.query(Bookshelf).filter(
        Bookshelf.bookshelf_title.ilike(f'%{search_term}%')
    ).all()
    bookshelf_data = []
    for bookshelf in bookshelfs:
        # 查询当前项目的评论数量
        review_count = count_review(bookshelf.bookshelf_id, 'bookshelf')
        # 查询当前点赞数量
        like_count = count_like(bookshelf.bookshelf_id, 'bookshelf')
        # 查询当前项目的收藏数量
        collect_count = count_collect(bookshelf.bookshelf_id, 'bookshelf')
        bookshelf_data_now = {
            'bookshelf_id': bookshelf.bookshelf_id,
            'bookshelf_user': bookshelf.bookshelf_user_id,
            'bookshelf_title': bookshelf.bookshelf_title,
            'bookshelf_time': bookshelf.bookshelf_time.strftime('%Y-%m-%d %H:%M:%S'),
            'bookshelf_see': bookshelf.bookshelf_see,
            'review_count': review_count,
            'like_count': like_count,
            'collect_count': collect_count
        }
        bookshelf_data.append(bookshelf_data_now)
    if page_num:
        page_now = int(data.get('page', 1) - 1) * page_num
        num = inquire_total_page(len(bookshelf_data), page_num)
        if page_now >= len(bookshelf_data):
            bookshelf_data = []
        else:
            bookshelf_data = get_page_data(bookshelf_data, data.get('page', 1)-1, page_num)

            # bookshelf_data = bookshelf_data[page_now:page_now + page_num]
        response = {
            'bookshelf_data': bookshelf_data,
            'total_page': num
        }
        return jsonify(response)
    response = {
        'bookshelf_data': bookshelf_data
    }
    return jsonify(response)


@blue_search.route('/api/search/dynamic', methods=['POST', 'GET'])
def search_dynamics_by_text_and_title():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    search_term = data.get('search')
    page_num = int(data.get('page_num', 0))

    dynamics = db.session.query(Dynamic).filter(
        (Dynamic.dynamic_text.ilike(f'%{search_term}%')) |
        (Dynamic.dynamic_title.ilike(f'%{search_term}%'))
    ).all()
    dynamics_data = []
    for dynamic in dynamics:
        # 查询当前项目的评论数量
        review_count = count_review(dynamic.dynamic_id, 'dynamic')
        # 查询当前点赞数量
        like_count = count_like(dynamic.dynamic_id, 'dynamic')
        # 查询当前项目的收藏数量
        collect_count = count_collect(dynamic.dynamic_id, 'dynamic')
        dynamic_data_now = {
            'dynamic_id': dynamic.dynamic_id,
            'dynamic_user': dynamic.dynamic_user,
            'dynamic_title': dynamic.dynamic_title,
            'dynamic_text': dynamic.dynamic_text,
            'dynamic_time': dynamic.dynamic_time.strftime('%Y-%m-%d %H:%M:%S'),
            'dynamic_see': dynamic.dynamic_see,
            'review_count': review_count,
            'like_count': like_count,
            'collect_count': collect_count
        }
        dynamics_data.append(dynamic_data_now)
    if page_num:
        page_now = (int(data.get('page', 1)) - 1) * page_num
        num = inquire_total_page(len(dynamics_data), page_num)
        if page_now >= len(dynamics_data):
            dynamics_data = []
        else:
            dynamics_data = get_page_data(dynamics_data, data.get('page', 1)-1, page_num)

            # dynamics_data = dynamics_data[page_now:page_now + page_num]
        response = {
            'dynamics_data': dynamics_data,
            'total_page': num
        }
        return jsonify(response)
    response = {
        'dynamics_data': dynamics_data
    }
    return jsonify(response)


@blue_search.route('/api/search/question', methods=['POST', 'GET'])
def search_questions_by_text_and_title():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    search_term = data.get('search')
    page_num = int(data.get('page_num', 0))

    questions = db.session.query(Questions).filter(
        (Questions.question_text.ilike(f'%{search_term}%')) |
        (Questions.question_title.ilike(f'%{search_term}%'))
    ).all()

    question_data = []
    for question in questions:
        # 查询当前项目的评论数量
        review_count = count_review(question.question_id, 'question')
        # 查询当前点赞数量
        like_count = count_like(question.question_id, 'question')
        # 查询当前项目的收藏数量
        collect_count = count_collect(question.question_id, 'question')
        question_data_now = {
            'question_id': question.question_id,
            'question_user': question.question_user,
            'question_title': question.question_title,
            'question_text': question.question_text,
            'question_integral': question.question_integral,
            'question_answer': question.question_answer,
            'question_time': question.question_time.strftime('%Y-%m-%d %H:%M:%S'),
            'question_see': question.question_see,
            'review_count': review_count,
            'like_count': like_count,
            'collect_count': collect_count
        }
        question_data.append(question_data_now)
    if page_num:
        page_now = int(data.get('page', 1)- 1) * page_num
        num = inquire_total_page(len(question_data), page_num)
        if page_now >= len(question_data):
            question_data = []
        else:
            question_data = get_page_data(question_data, data.get('page', 1)-1, page_num)

            # question_data = question_data[page_now:page_now + page_num]
        response = {
            'question_data': question_data,
            'total_page': num
        }
        return jsonify(response)
    response = {
        'question_data': question_data
    }
    return jsonify(response)


@blue_search.route('/api/search/user', methods=['POST', 'GET'])
def search_users_by_name_and_introduce():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    search_term = data.get('search')
    page_num = int(data.get('page_num', 0))

    users = db.session.query(Users).filter(
        (Users.user_name.ilike(f'%{search_term}%')) |
        (Users.user_introduce.ilike(f'%{search_term}%'))
    ).all()
    user_data = []
    for user in users:
        pic = Picture.query.filter_by(picture_ob_type='user', picture_object=user.user_id).first()
        user_now = {
            'user_id': user.user_id,
            'user_name': user.user_name,
            'user_introduce': user.user_introduce,
            'user_grade': user.user_grade,
            'user_attention': user.user_attention,
            'user_fan': user.user_fan,
            'user_upgrade': user.user_upgrade,
            'user_fraction': user.user_fraction,
            'user_picture': pic.picture_address
        }
        user_data.append(user_now)

    if page_num:
        page_now = (int(data.get('page', 1)) - 1) * page_num
        num = inquire_total_page(len(user_data), page_num)
        if page_now >= len(user_data):
            user_data = []
        else:
            user_data = user_data[page_now:page_now + page_num]
        response = {
            'user_data': user_data,
            'total_page': num
        }
        return jsonify(response)
    response = {
        'user_data': user_data
    }
    return jsonify(response)


# 根据标签查询内容
@blue_search.route('/api/tag/content', methods=['POST', 'GET'])
def query_tag_content():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    user_id = data.get('id')
    tag_name = data.get('tag_name')
    page_num = int(data.get('page_num', 0))
    blacklist_id = Blacklist.query.filter_by(blacklist_parent=user_id).all()
    blacklist_id_list = [blacklist_id.blacklist_child for blacklist_id in blacklist_id]

    tag = Tag.query.filter_by(tag_name=tag_name).first()
    tag_id = tag.tag_id
    textpag1 = TagRelation.query.filter_by(tagrelation_tag_id=tag_id, tagrelation_type="program").all()
    textpag2 = TagRelation.query.filter_by(tagrelation_tag_id=tag_id, tagrelation_type="dynamic").all()
    program_data_list = []
    dynamic_data_list = []

    if textpag1 is not None:
        for program in textpag1:
            program_id = program.tagrelation_object
            program_now = Questions.query.filter_by(question_id=program_id).first()
            program_data_list = []
            # 如果有黑名单上的用户id就不发送给前端
            if program_now.question_user not in blacklist_id_list:
                # 查询当前项目的评论数量
                review_count = count_review(program_now.question_id, 'question')
                # 查询当前点赞数量
                like_count = count_like(program_now.question_id, 'question')
                # 查询当前项目的收藏数量
                collect_count = count_collect(program_now.question_id, 'question')
                program_data = {
                    'question_id': program_now.question_id,
                    'question_user': program_now.question_user,
                    'question_title': program_now.question_title,
                    'question_text': program_now.question_text,
                    'question_integral': program_now.question_integral,
                    'question_answer': program_now.question_answer,
                    'question_time': program_now.question_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'review_count': review_count,
                    'like_count': like_count,
                    'collect_count': collect_count
                }
                program_data_list.append(program_data)
    if textpag2 is not None:
        for dynamic in textpag2:
            dynamic_id = dynamic.tagrelation_object
            dynamic_now = Dynamic.query.filter_by(dynamic_id=dynamic_id).first()
            dynamic_data_list = []
            # 如果有黑名单上的用户id就不发送给前端
            if dynamic_now.dynamic_user not in blacklist_id_list:
                # 查询当前项目的评论数量
                review_count = count_review(dynamic_now.dynamic_id, 'dynamic')
                # 查询当前点赞数量
                like_count = count_like(dynamic_now.dynamic_id, 'dynamic')
                # 查询当前项目的收藏数量
                collect_count = count_collect(dynamic_now.dynamic_id, 'dynamic')
                dynamic_data = {
                    'dynamic_id': dynamic_now.dynamic_id,
                    'dynamic_user': dynamic_now.dynamic_user,
                    'dynamic_title': dynamic_now.dynamic_title,
                    'dynamic_text': dynamic_now.dynamic_text,
                    'dynamic_time': dynamic_now.dynamic_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'review_count': review_count,
                    'like_count': like_count,
                    'collect_count': collect_count
                }
                dynamic_data_list.append(dynamic_data)
    if page_num:
        object_page = int(data.get('page', 1)- 1) * page_num
        if object_page >= len(program_data_list):
            program_data_list = []
        else:
            program_data_list = get_page_data(program_data_list, data.get('page', 1), page_num)

        if object_page >= len(dynamic_data_list):
            dynamic_data_list = []
        else:
            dynamic_data_list = get_page_data(dynamic_data_list, data.get('page', 1), page_num)


    response = {
        'program_data': program_data_list,
        'program_num': len(program_data_list),
        'dynamic_data': dynamic_data_list,
        'dynamic_num': len(dynamic_data_list)
    }
    return jsonify(response), 200


# 查询某个用户的项目
@blue_search.route('/api/user/type', methods=['POST', 'GET'])
def query_user_type():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    print(data)
    object_type = data.get('type')
    user_id = data.get('id')
    if object_type == "user":
        user_now = Users.query.filter_by(user_id=user_id).first()
        pic = Picture.query.filter_by(picture_ob_type='user', picture_object=user_id).all()
        attention_now = AttentionFan.query.filter_by(af_parent=user_id).all()
        attention_data = [{
            'attention_id': att.af_child,
        } for att in attention_now]

        fans_now = AttentionFan.query.filter_by(af_child=user_id).all()
        fans_data = [{
            'fans_id': fan.af_parent,
        } for fan in fans_now]
        user_data = {
            'user_id': user_now.user_id,
            'user_name': user_now.user_name,
            'user_number': user_now.user_number,
            'user_password': user_now.user_password,
            'user_fan': user_now.user_fan,
            'user_attention': user_now.user_attention,
            'user_state': user_now.user_state,
            'user_introduce': user_now.user_introduce,
            'user_fraction': user_now.user_fraction,
            'user_grade': user_now.user_grade,
            'is_active': user_now.is_active
        }

        response = {
            'user_data': user_data,
            'attention_data': attention_data,
            'fans_data': fans_data,
            'user_pic': pic
        }
        return jsonify(response), 200
    elif object_type == "questions":
        # 查看分不分页
        page_num = int(data.get('page_num', 0))
        dyn = Questions.query.filter_by(question_user=user_id).all()
        if dyn is None:
            return {'message': '该用户未创建问题'}, 201
        questions_data = []
        for question in dyn:
            # 查询当前项目的评论数量
            review_count = count_review(question.question_id, 'question')
            # 查询当前点赞数量
            like_count = count_like(question.question_id, 'question')
            # 查询当前项目的收藏数量
            collect_count = count_collect(question.question_id, 'question')
            # 查询当前项目的图片
            pic_list = ger_pic_list(question.question_id, 'question')
            questions_data_now = {
                'question_id': question.question_id,
                'question_user': question.question_user,
                'question_title': question.question_title,
                'question_text': question.question_text,
                'question_integral': question.question_integral,
                'question_answer': question.question_answer,
                'question_time': question.question_time.strftime('%Y-%m-%d %H:%M:%S'),
                'review_count': review_count,
                'like_count': like_count,
                'collect_count': collect_count,
                'pic_list': pic_list
            }
            questions_data.append(questions_data_now)
        if page_num:
            page_now = int(data.get('page', 1)- 1) * page_num
            if page_now >= len(questions_data):
                questions_data = []
            else:
                questions_data = get_page_data(questions_data, data.get('page', 1), page_num)

        response = {
            'questions_data': questions_data,
            'questions_num': len(questions_data)
        }
        return jsonify(response), 200
    elif object_type == "special":
        # 查看分不分页
        page_num = int(data.get('page_num', 0))
        spe = Special.query.filter_by(special_user=user_id).all()
        if spe is None:
            return {'message': '该用户未创建专栏'}, 201
        specials_data = []
        for special in spe:
            # 查询当前项目的评论数量
            review_count = count_review(special.special_id, 'special')
            # 查询当前点赞数量
            like_count = count_like(special.special_id, 'special')
            # 查询当前项目的收藏数量
            collect_count = count_collect(special.special_id, 'special')
            specials_data_now = {
                'special_id': special.special_id,
                'special_user': special.special_user,
                'special_title': special.special_title,
                'special_time': special.special_time.strftime('%Y-%m-%d %H:%M:%S'),
                'review_count': review_count,
                'like_count': like_count,
                'collect_count': collect_count
            }
            specials_data.append(specials_data_now)
        if page_num:
            page_now = int(data.get('page', 1)- 1) * page_num
            if page_now >= len(specials_data):
                specials_data = []
            else:
                specials_data = get_page_data(specials_data, data.get('page', 1), page_num)

        response = {
            'specials_data': specials_data,
            'specials_num': len(specials_data)
        }
        return jsonify(response), 200
    elif object_type == "dynamic":
        # 查看分不分页
        page_num = int(data.get('page_num', 0))
        dyn = Dynamic.query.filter_by(dynamic_user=user_id).all()
        if dyn is None:
            return {'message': '该用户未创建文章'}, 201
        dynamics_data = []
        for dynamic in dyn:
            # 查询当前项目的评论数量
            review_count = count_review(dynamic.dynamic_id, 'dynamic')
            # 查询当前点赞数量
            like_count = count_like(dynamic.dynamic_id, 'dynamic')
            # 查询当前项目的收藏数量
            collect_count = count_collect(dynamic.dynamic_id, 'dynamic')
            # 查询当前项目的图片列表
            pic_list = ger_pic_list(dynamic.dynamic_id, 'dynamic')
            dynamics_data_now = {
                'dynamic_id': dynamic.dynamic_id,
                'dynamic_user': dynamic.dynamic_user,
                'dynamic_title': dynamic.dynamic_title,
                'dynamic_text': dynamic.dynamic_text,
                'dynamic_time': dynamic.dynamic_time.strftime('%Y-%m-%d %H:%M:%S'),
                'review_count': review_count,
                'like_count': like_count,
                'collect_count': collect_count,
                'pic_list': pic_list
            }
            dynamics_data.append(dynamics_data_now)

        if page_num:
            page_now = int(data.get('page', 1)- 1) * page_num
            if page_now >= len(dynamics_data):
                dynamics_data = []
            else:
                dynamics_data = get_page_data(dynamics_data, data.get('page', 1), page_num)

        response = {
            'dynamics_data': dynamics_data,
            'dynamics_num': len(dynamics_data)
        }
        return jsonify(response), 200
    elif object_type == "bookshelf":
        # 查看分不分页
        page_num = int(data.get('page_num', 0))
        bse = Bookshelf.query.filter_by(bookshelf_user_id=user_id).all()
        if bse is None:
            return {'message': '该用户未创建书架'}, 201
        bookshelf_data = []
        for bookshelf in bse:
            # 查询当前项目的评论数量
            review_count = count_review(bookshelf.bookshelf_id, 'bookshelf')
            # 查询当前点赞数量
            like_count = count_like(bookshelf.bookshelf_id, 'bookshelf')
            # 查询当前项目的收藏数量
            collect_count = count_collect(bookshelf.bookshelf_id, 'bookshelf')
            bookshelf_data_now = {
                'bookshelf_id': bookshelf.bookshelf_id,
                'bookshelf_user': bookshelf.bookshelf_user_id,
                'bookshelf_title': bookshelf.bookshelf_title,
                'bookshelf_time': bookshelf.bookshelf_time.strftime('%Y-%m-%d %H:%M:%S'),
                'review_count': review_count,
                'like_count': like_count,
                'collect_count': collect_count
            }
            bookshelf_data.append(bookshelf_data_now)
        if page_num:
            page_now = int(data.get('page', 1)- 1) * page_num
            if page_now >= len(bookshelf_data):
                bookshelf_data = []
            else:
                bookshelf_data = get_page_data(bookshelf_data, data.get('page', 1), page_num)

        response = {
            'bookshelf_data': bookshelf_data,
            'bookshelf_num': len(bookshelf_data)
        }
        return jsonify(response), 200
    else:
        return {'message': '未识别的type字符串'}, 201


# 查询用户是否点赞该项目
@blue_search.route('/api/type/like_now', methods=['POST', 'GET'])
def query_type_like_now():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    object_id = data.get('object_id')
    object_type = data.get('object_type')
    user_id = data.get('id')
    like_now = Like.query.filter_by(like_user=user_id, like_object=object_id, like_type=object_type).first()
    if like_now is not None:
        return {'message': '已点赞'}, 200
    else:
        return {'message': '未点赞'}, 200


# 带有模糊搜索的标签名称的查询，还得带有该标签连接了多少文章和问题
@blue_search.route('/api/search/tag', methods=['POST', 'GET'])
def query_tag_name():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    data = request.get_json()
    print(data)
    search = data.get('search')
    print(search)
    page_num = int(data.get('page_num', 0))
    tags_search = Tag.query.filter(Tag.tag_name.ilike(f'%{search}%')).all()
    tag_search_data = []
    for tag in tags_search:
        tag_id = tag.tag_id
        textpag1 = TagRelation.query.filter_by(tagrelation_object=tag_id, tagrelation_type="program").all()
        textpag2 = TagRelation.query.filter_by(tagrelation_object=tag_id, tagrelation_type="dynamic").all()
        pro_num = len(textpag1)
        dym_num = len(textpag2)
        tag_data = {
            'pro_num': pro_num,
            'dym_num': dym_num,
            'tag_name': tag.tag_name,
            'tag_id': tag.tag_id,
            'tag_time': tag.tag_time
        }

        tag_search_data.append(tag_data)
    num1 = len(tag_search_data)
    if page_num:
        page_now = int(data.get('page', 1) - 1) * page_num
        num = inquire_total_page(len(tag_search_data), page_num)
        if page_now >= len(tag_search_data):
            tag_search_data = []
        else:
            tag_search_data = get_page_data(tag_search_data, data.get('page', 1), page_num)
        response = {
            'tag_search_data': tag_search_data,
            'total_page': num,
            'total_num': num1
        }
        return jsonify(response)
    response = {
        'tag_search_data': tag_search_data
    }
    return jsonify(response)
